package cn.edu.zafu.bigdata.zqt.appendToFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;

public class main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入文件路径：");
        String filePath = scanner.nextLine();

        System.out.print("请输入内容：");
        String content = scanner.nextLine();
        appendToFile(filePath, content);
        readFromFile(filePath);
    }

    private static void readFromFile(String filePath) {
        try {
            byte[] bytes = Files.readAllBytes(Paths.get(filePath));
            System.out.println("文件内容为：" + new String(bytes));
        }
        catch (IOException e) {
            System.out.println("读取文件失败：" + e.getMessage());
        }
    }

    public static void appendToFile(String filePath, String content) {
        try {
            Files.write(Paths.get(filePath), content.getBytes());
            System.out.println("内容已追加到文件：" + filePath);
        }
        catch (Exception e) {
            System.out.println("文件不存在，创建新文件");
            File file = new File(filePath);
            try {
                Files.write(Paths.get(filePath), content.getBytes());
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }


}
